package com.example.sample;

import com.ohos.volley.Request;
import com.ohos.volley.RequestQueue;
import com.ohos.volley.ext.LocalHiLog;
import com.ohos.volley.toolbox.StringRequest;
import ohos.aafwk.ability.delegation.AbilityDelegatorRegistry;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

public class ExampleOhosTest {
    private static final String TAG = "TestVolley";

    private RequestQueue mRequestQueue;

    @Test
    public void testBundleName() {
        final String actualBundleName = AbilityDelegatorRegistry.getArguments().getTestBundleName();
        assertEquals("com.example.sample", actualBundleName);
    }

    @Before
    public void setUp() {
        mRequestQueue = VolleyHelper.getInstance(AbilityDelegatorRegistry.getAbilityDelegator().getAppContext()).getRequestQueue();
    }

    @Test
    public void testGet() {
        final Boolean[] resultFlg = {false};
        final CountDownLatch signal = new CountDownLatch(1);
        LocalHiLog.info(TAG, "before request");

        AbilityDelegatorRegistry.getAbilityDelegator().runOnUIThreadSync(new Runnable() {
            @Override
            public void run() {
                StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://httpbin.org/get",
                        response -> {
//                                assertEquals(200, statusCode);
                            LocalHiLog.info(TAG, "onResponse");

                            assertNull(null);
                            signal.countDown();
                            resultFlg[0] = true;
                        }, error -> LocalHiLog.info(TAG, "onFailure"));
                mRequestQueue.add(stringRequest);
            }
        });

        try {
            LocalHiLog.info(TAG, "signal.await");
            signal.await(30, TimeUnit.SECONDS); // wait for callback
        } catch (InterruptedException e) {
            LocalHiLog.debug("Exception-->",e.getMessage());
        }
        assertTrue(resultFlg[0]);
        assertEquals(0, signal.getCount());
    }
}